﻿using System;
using System.Diagnostics;

namespace AzurePlugin.Converter
{
    public class ConverterLogger
    {
        private static readonly ConverterTraceSource _traceSource = new ConverterTraceSource(typeof(ConverterLogger).FullName);
        private static ConverterLogger _instance;

        public static ConverterLogger Instance
        {
            get
            {
                if (_instance == null)
                    throw new InvalidOperationException("Please call Init method before using logger instance");

                return _instance;
            }
        }

        public static void Init(string filePath)
        {
            _instance = new ConverterLogger(filePath);
        }

        public static void Close()
        {
            _instance = null;
            _traceSource.Close();
        }

        protected ConverterLogger(string filePath)
        {
            var listener = new TextWriterTraceListener(filePath)
                               {
                                   Filter = new SourceFilter(typeof (ConverterLogger).FullName),
                                   TraceOutputOptions = TraceOptions.DateTime | TraceOptions.ThreadId
                               };

            _traceSource.Listeners.Add(listener);
            _traceSource.Switch.Level = SourceLevels.All;
        }

        public void Info(string message)
        {
            _traceSource.TraceInformation(message);
            _traceSource.Flush();
        }

        public void Info(string format, params object [] replacements)
        {
            _traceSource.TraceInformation(string.Format(format, replacements));
            _traceSource.Flush();
        }

        public void Warning(string message)
        {
            _traceSource.TraceWarning(message);
            _traceSource.Flush();
        }

        public void Error(Exception exception)
        {
            _traceSource.TraceError(exception);
            _traceSource.Flush();
        }

        public void Error(string message)
        {
            _traceSource.TraceError(message);
            _traceSource.Flush();
        }
    }
}
